package com.jspgou.cms.action.directive;

import static com.jspgou.cms.Constants.SHOP_SYS;
import static freemarker.template.ObjectWrapper.DEFAULT_WRAPPER;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import com.jspgou.cms.action.directive.abs.WebDirective;
import com.jspgou.cms.manager.ShopYushouMng;
import com.jspgou.common.page.Pagination;
import com.jspgou.common.web.freemarker.DirectiveUtils;
import com.jspgou.core.entity.Website;
import com.jspgou.core.manager.WebsiteMng;

import freemarker.core.Environment;
import freemarker.template.ObjectWrapper;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;

public class YuShouOrderPageDirective extends WebDirective{
	
	public static final String TPL_NAME="ArticlePage";

	public void execute(Environment env, Map params, TemplateModel[] loopVars,
			TemplateDirectiveBody body) throws TemplateException, IOException {
		Website web=getWeb(env,params,websiteMng);
		Integer pageSize=getCount(params);
		Integer count=getCount(params);
		Long memberId=getLong("memberId",params);
		Long storeId=getLong("storeId",params);
		//预售订单状态
		String yuStatus=getString("yuStatus",params);
		SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd");
		//预售订单创建时间
		String createTime=getString("createTime",params);
		Short status=null;
		Date start=null;
		if(!StringUtils.isBlank(createTime)){
			try {
				start=df.parse(createTime);
			} catch (java.text.ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		if(yuStatus!=null){
			status=Short.parseShort(yuStatus);
		}
		Pagination pagination=shopYushouMng.getPage(getPageNo(env), count, memberId,storeId, start,status);
		Map<String,TemplateModel> paramWarp=new HashMap<String,TemplateModel>(params);
		paramWarp.put(OUT_PAGINATION, ObjectWrapper.DEFAULT_WRAPPER.wrap(pagination));
		paramWarp.put(OUT_LIST, DEFAULT_WRAPPER.wrap(pagination.getList()));
		Map<String, TemplateModel> origMap = DirectiveUtils.addParamsToVariable(env, paramWarp);
		if (isInvokeTpl(params)) {
	         includeTpl(SHOP_SYS, TPL_NAME, web, params, env);
       } else {
       	renderBody(env, loopVars, body);
       }
       DirectiveUtils.removeParamsFromVariable(env, paramWarp, origMap);
	}
	
	private void renderBody(Environment evn, TemplateModel[] loopVars,
			TemplateDirectiveBody body) throws TemplateException, IOException {
		body.render(evn.getOut());
	}
	
	@Autowired
	private WebsiteMng websiteMng;
	@Autowired
	private ShopYushouMng shopYushouMng;
}
